<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\middleware;

use app\dao\setting\SystemAdminDao;
use app\dao\setting\SystemRoleDao;
use kitego\enum\ApiCodeEnum;
use kitego\extend\login\admin\AdminLoginBase;
use kitego\traits\AdminAuthTrait;
use think\Request;

class AdminLoginMiddleware
{
    use AdminAuthTrait;

    private $request;

    /**
     * 后台登陆验证中间件
     */
    public function handle(Request $request, \Closure $next)
    {
        $this->request = $request;

        // 放行无需鉴权的接口
        if ($request->invokeController->checkSafeAction()) return $next($request);

        $token = $request->header(config('cookie.token_name', 'Authorization'));
        if (empty($token)) abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');

        $token = trim(ltrim($token, 'Bearer'));
        $this->request->adminAccessToken = $token;

        // 检测Token是否在注销列表中
        $user = app()->make(AdminLoginBase::class)->checkLogoutList($token);

        // 校验管理员
        $systemAdmin = $this->checkAdminInfo($user);

        // 校验管理员角色
        $this->checkAdminRole($systemAdmin);

        return $next($this->request);
    }

    /**
     * 获取管理员信息
     */
    public function checkAdminInfo($user)
    {
        if (
            empty($user) ||
            empty($user->userId) ||
            empty($user->nickname) ||
            empty($user->avatar) ||
            empty($user->adminRole)
        ) {
            abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');
        }

        $this->request->userId = $user->userId;
        $this->request->nickname = $user->nickname;
        $this->request->avatar = $user->avatar;
        $this->request->adminRole = $user->adminRole;

        // 校验管理员信息
        $systemAdmin = app()->make(SystemAdminDao::class)->find($this->request->userId);
        $this->request->userUuid = $systemAdmin->uuid;

        if (
            !$systemAdmin ||
            $systemAdmin['status'] == 2 ||
            $systemAdmin['delete_flag'] == 2 ||
            empty($systemAdmin['role_id'])
        ) {
            abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');
        }

        return $systemAdmin;
    }

    /**
     * 校验管理员角色
     */
    private function checkAdminRole($systemAdmin)
    {
        $adminRoleIdArr = explode(',', $systemAdmin['role_id']);
        $roleWhere[] = ['id', 'in', $adminRoleIdArr];
        $roleWhere[] = ['status', '=', 1];
        $roleWhere[] = ['delete_flag', '=', 0];
        $adminRoleQuery = app()->make(SystemRoleDao::class)->getColumn($roleWhere, 'menu_ids, alias');
        if (empty($adminRoleQuery) || count($adminRoleQuery) != count($adminRoleIdArr)) {
            abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');
        }

        // 管理员角色ids
        $this->request->adminRoleId = $adminRoleIdArr;
        $this->request->adminRoleAlias = array_column($adminRoleQuery, 'alias');

        $adminRoleMenuIds = [];
        foreach ($adminRoleQuery as $va) {
            if (empty($adminRoleMenuIds)) {
                $adminRoleMenuIds = explode(',', $va['menu_ids']);
            } else {
                $adminRoleMenuIds = array_unique(array_merge($adminRoleMenuIds, explode(',', $va['menu_ids'])));
            }
        }

        $this->request->adminRoleMenuIds = $adminRoleMenuIds;
    }
}
